--
-- Author: Millson Zhou
-- Date: 2014-07-03 21:06:14
--
local Util = {}

function Util.split(delim, str)   
    if string.find(str, delim) == nil then  
        return { str }  
    end  

    local result = {}  
    local pat = "(.-)" .. delim .. "()"   
    local nb = 0  
    local lastPos 
    for part, pos in string.gfind(str, pat) do  
        nb = nb + 1
        
        result[nb] = part
        if tonumber(part) ~= nil or tonumber(part) == 0 then
            result[nb] = tonumber(part)
        end
        lastPos = pos
        if nb == maxNb then break end  
    end

    local last_part = string.sub(str, lastPos)
    result[nb + 1] = last_part

    if tonumber(last_part) then
        result[nb + 1] = tonumber(last_part)
    end

    return result   
end

function Util.var_dump(data)
    local max = 0
    local function var_dump_tbl(tbl, tab)
        local ret = ""
        local last_tab = tab
        if type(tbl) == 'string' then
            return '"' .. tostring(tbl) .. '"'
        elseif type(tbl) ~= 'table' then
            return tostring(tbl)
        else
            ret = ret .. "{\n"
            tab = tab .. "\t"
            for k,v in ipairs(tbl) do
                if type(k) == 'string' then
                    k = '"' .. k .. '"'
                end
                ret = ret .. tab .. tostring(k) .. " = " .. var_dump_tbl(v, tab) .. "\n"
            end
            ret = ret .. last_tab .. "}\n"
        end

        return ret
    end
    print(var_dump_tbl(data, ""))
end

function Util.parse_csv(filepath, start)
    local lines = {}
    for line in io.lines(filepath) do
        table.insert(lines, line)
    end

    if not start then
        start = 1
    end

    local data = {}
    for i=start,#lines do
        table.insert(data, Util.split(",", string.gsub(lines[i], "^%s*(.-)%s*$", "%1")))
    end

    return data
end

return Util